﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;
using SZHL.Data;
using SZHL.UI.AppCode;

namespace SZHL.UI.API
{
    /// <summary>
    /// IMAPI 的摘要说明
    /// </summary>
    public class IMAPI : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (HttpContext.Current.Request.HttpMethod.ToUpper() == "GET")
            {
                Auth();
            }
            else if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
            {
                string token = WXHelp.IMToken;//"9f02rOXenCEWIsnMYd";
                string encodingAESKey = WXHelp.IMAesKey;//"M7gwtCtryDvzzsq86LbIx2K1AlWYG1LoM76UMtUM2yu";
                string corpId = WXHelp.corpId;//"wxf285796b249c0cf6";

                string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature
                string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
                string nonce = HttpContext.Current.Request.QueryString["nonce"];

                // 获得客户端RAW HttpRequest  
                StreamReader srResult = new StreamReader(context.Request.InputStream);
                string str = srResult.ReadToEnd();

                string strde=string.Empty;

                Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(token, encodingAESKey, corpId);
                wxcpt.DecryptMsg(signature, timestamp, nonce, str, ref strde);

            //string strde = HttpContext.Current.Request.QueryString[0];

                XmlDocument XmlDocument = new XmlDocument();
                XmlDocument.LoadXml(HttpContext.Current.Server.UrlDecode(strde));

                string AgentType = string.Empty;
                string ToUserName = string.Empty;
                string ItemCount = string.Empty;
                string PackageId = string.Empty;
                string Item = string.Empty;

                #region XML文档处理
                foreach (XmlNode xn in XmlDocument.ChildNodes[0].ChildNodes)
                {
                    if (xn.Name == "AgentType")
                    {
                        AgentType = xn.InnerText;
                    }
                    if (xn.Name == "ToUserName")
                    {
                        ToUserName = xn.InnerText;
                    }
                    if (xn.Name == "ItemCount")
                    {
                        ItemCount = xn.InnerText;
                    }
                    if (xn.Name == "PackageId")
                    {
                        PackageId = xn.InnerText;
                    }
                    if (xn.Name == "Item")
                    {
                        Item += xn.InnerXml;

                        if (xn.ChildNodes[2].InnerText == "event")
                        {
                            #region event处理
                            ZH_JSTX zj = new ZH_JSTX();
                            foreach (XmlNode xnc in xn.ChildNodes)
                            {
                                if (xnc.Name == "FromUserName")
                                {
                                    zj.FromUserName = xnc.InnerText;
                                }
                                if (xnc.Name == "MsgType")
                                {
                                    zj.MsgType = xnc.InnerText;
                                }
                                if (xnc.Name == "Event")
                                {
                                    zj.Event = xnc.InnerText;
                                }
                                if (xnc.Name == "ChatId")
                                {
                                    zj.ChatId = xnc.InnerText;
                                }
                                if (xnc.Name == "Name")
                                {
                                    zj.Name = xnc.InnerText;
                                }
                                if (xnc.Name == "Owner")
                                {
                                    zj.Owner = xnc.InnerText;
                                }
                                if (xnc.Name == "UserList")
                                {
                                    zj.UserList = xnc.InnerText;
                                }
                                if (xnc.Name == "AddUserList")
                                {
                                    zj.AddUserList = xnc.InnerText;
                                }
                                if (xnc.Name == "DelUserList")
                                {
                                    zj.DelUserList = xnc.InnerText;
                                }
                                if (xnc.Name == "CreateTime")
                                {
                                    DateTime time = DateTime.MinValue;
                                    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                                    time = startTime.AddSeconds(int.Parse(xnc.InnerText));

                                    zj.CreateTime = time;
                                }
                                if (xnc.ChildNodes.Count > 1)
                                {
                                    foreach (XmlNode xncn in xnc.ChildNodes)
                                    {
                                        if (xncn.Name == "ChatId")
                                        {
                                            zj.ChatId = xncn.InnerText;
                                        }
                                        if (xncn.Name == "Name")
                                        {
                                            zj.Name = xncn.InnerText;
                                        }
                                        if (xncn.Name == "Owner")
                                        {
                                            zj.Owner = xncn.InnerText;
                                        }
                                        if (xncn.Name == "UserList")
                                        {
                                            zj.UserList = xncn.InnerText;
                                        }
                                    }
                                }
                            }
                            new ZH_JSTXB().Insert(zj);
                            #endregion
                        }
                        else if (xn.ChildNodes[2].InnerText == "text" || xn.ChildNodes[2].InnerText == "image")
                        {
                            #region text、image处理
                            ZH_JSTX_Item zj = new ZH_JSTX_Item();
                            foreach (XmlNode xnc in xn.ChildNodes)
                            {
                                if (xnc.Name == "FromUserName")
                                {
                                    zj.FromUserName = xnc.InnerText;
                                }
                                if (xnc.Name == "MsgType")
                                {
                                    zj.MsgType = xnc.InnerText;
                                }
                                if (xnc.Name == "Event")
                                {
                                    zj.Event = xnc.InnerText;
                                }
                                if (xnc.Name == "Content")
                                {
                                    zj.Content = xnc.InnerText;
                                }
                                if (xnc.Name == "MsgId")
                                {
                                    zj.MsgId = xnc.InnerText;
                                }
                                
                                if (xnc.Name == "PicUrl")
                                {
                                    zj.PicUrl = xnc.InnerText;
                                }
                                if (xnc.Name == "MediaId")
                                {
                                    zj.MediaId = xnc.InnerText;
                                }
                                if (xnc.Name == "CreateTime")
                                {
                                    DateTime time = DateTime.MinValue;
                                    DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                                    time = startTime.AddSeconds(int.Parse(xnc.InnerText));
                                    zj.CreateTime = time;
                                }
                                if (xnc.ChildNodes.Count > 1)
                                {
                                    foreach (XmlNode xncn in xnc.ChildNodes)
                                    {
                                        if (xncn.Name == "Type")
                                        {
                                            zj.Type = xncn.InnerText;
                                        }
                                        if (xncn.Name == "Id")
                                        {
                                            zj.UID = xncn.InnerText;
                                        }
                                    }
                                }
                            }
                            new ZH_JSTX_ItemB().Insert(zj);
                            #endregion
                        }
                    }
                }
                #endregion

                string path = HttpContext.Current.Request.MapPath("/");
                if (!Directory.Exists(path + "/log/"))
                {
                    Directory.CreateDirectory(path + "/log/");
                }

                string name = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                if (!File.Exists(path + "/log/" + name))
                {
                    FileInfo myfile = new FileInfo(path + "/log/" + name);
                    FileStream fs = myfile.Create();
                    fs.Close();
                }

                string strzc = AgentType + "\r\n" + ToUserName + "\r\n" + ItemCount + "\r\n" + PackageId + "\r\n" + Item + "\r\n";

                StreamWriter sw = File.AppendText(path + "/log/" + name);
                sw.WriteLine(strde + "\r\n" + strzc + "\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                sw.Flush();
                sw.Close();

                HttpContext.Current.Response.Write(PackageId);
                HttpContext.Current.Response.End();
            }
            
        }

        /// <summary>
        /// 成为开发者的第一步，验证并相应服务器的数据
        /// </summary>
        private void Auth()
        {
            string token = WXHelp.IMToken;//"9f02rOXenCEWIsnMYd";//从配置文件获取Token

            string encodingAESKey = WXHelp.IMAesKey;//"M7gwtCtryDvzzsq86LbIx2K1AlWYG1LoM76UMtUM2yu";//从配置文件获取EncodingAESKey

            string corpId = WXHelp.corpId;//"wxf285796b249c0cf6";//从配置文件获取corpId

            string echoString = HttpContext.Current.Request.QueryString["echoStr"];
            string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature
            string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            string nonce = HttpContext.Current.Request.QueryString["nonce"];

            string decryptEchoString = "";
            if (CheckSignature(token, signature, timestamp, nonce, corpId, encodingAESKey, echoString, ref decryptEchoString))
            {
                if (!string.IsNullOrEmpty(decryptEchoString))
                {
                    HttpContext.Current.Response.Write(decryptEchoString);
                    HttpContext.Current.Response.End();
                }
            }
        }

        /// <summary>
        /// 验证企业号签名
        /// </summary>
        /// <param name="token">企业号配置的Token</param>
        /// <param name="signature">签名内容</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">nonce参数</param>
        /// <param name="corpId">企业号ID标识</param>
        /// <param name="encodingAESKey">加密键</param>
        /// <param name="echostr">内容字符串</param>
        /// <param name="retEchostr">返回的字符串</param>
        /// <returns></returns>
        public bool CheckSignature(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr)
        {
            Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(token, encodingAESKey, corpId);
            int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr);
            if (result != 0)
            {
                //LogTextHelper.Error("ERR: VerifyURL fail, ret: " + result);
                return false;
            }

            return true;

            //ret==0表示验证成功，retEchostr参数表示明文，用户需要将retEchostr作为get请求的返回参数，返回给企业号。
            // HttpUtils.SetResponse(retEchostr);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}